﻿using System.Threading.Tasks;
using LearnASPNETCore.Models;
using LearnASPNETCore.Services;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCore.Controllers
{
    public class EmployeeController:Controller
    {
        private readonly IDepartmentService _departmentService;
        private readonly IEmployeeService _employeeService;

        public EmployeeController(IDepartmentService departmentService, IEmployeeService employeeService)
        {
            _departmentService = departmentService;
            _employeeService = employeeService;
        }

        //列出某一个部门下的所有员工
        public async Task<IActionResult> Index(int departmentId)
        {
            var department = await _departmentService.GetById(departmentId);


            ViewBag.Title = $"Employees of {department.Name}";
            ViewBag.DepartmentId = departmentId;

            var employees = await _employeeService.GetByDepartmentId(departmentId);

            return View(employees);
        }

        //针对部门添加员工
        public IActionResult Add(int departmentId)
        {
            ViewBag.Title = "Add Employee";
            //返回一个设置好部门ID的model
            return View(new Employee
            {
                DepartmentId = departmentId
            });
        }

        [HttpPost]
        //添加新员工提交之后执行
        public async Task<IActionResult> Add(Employee model)
        {
            //如果model属性合法
            if (ModelState.IsValid)
            {
                await _employeeService.Add(model);
            }
            //跳转到index
            return RedirectToAction(nameof(Index), new {departmentId = model.DepartmentId});
        }

        //解雇员工
        public async Task<IActionResult> Fire(int employeeId)
        {
            var employee = await _employeeService.Fire(employeeId);
            //解雇后跳转到index
            return RedirectToAction(nameof(Index), new {departmentId = employee.DepartmentId});
        }
    }
}